<template>
  <div class="login-container">
    <!-- 头部 -->
    <van-nav-bar title="登录">
      <template #left>
        <img class="logo" src="@/assets/images/logo.png" />
      </template>
    </van-nav-bar>

    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.tel"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        name="code"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="rules.password"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" :loading="isloading" loading-text="登录中..." >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { LoginAPI } from '../../api/login'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      rules: {
        // 账号校验
        tel: [
          // 必填
          {
            required: true,
            message: '请输入正确的手机号',
            trigger: 'onChange'
          },
          // 合法
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请填写手机号',
            trigger: 'onChange'
          }
        ],
        // 密码校验
        password: [
          // 必填
          {
            required: true,
            message: '请输入正确的密码',
            trigger: 'onChange'
          },
          // 合法
          {
            pattern: /^\d{6}$/,
            message: '请填写密码',
            trigger: 'onChange'
          }
        ]
      },
      // 登录表单数据
      formLogin: {
        // 手机号
        mobile: '13888888888',
        // 验证码
        code: '246810' // 默认只能用246810后台规定了
      },
      isloading: false
    }
  },
  methods: {
    ...mapMutations(['settoken', 'setrefresh_token']),
    // 登录按钮提交事件 --只有全部通过校验才会执行这个函数
    async onSubmit () {
      this.isloading = true
      try {
        const res = await LoginAPI(this.formLogin)

        this.settoken(res.data.data.token)
        this.setrefresh_token(res.data.data.refresh_token)
        Notify({ type: 'success', message: '登陆成功' })
        this.$router.push({
          path: '/layout'
        })
      } catch (err) {
        Notify({ type: 'danger', message: '用户名密码不正确' })
      } finally {
        // 这里不管成功还是失败,都要将按钮解禁
        this.isloading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
// .van-nav-bar {
//   background: #007bff;
//   /* /deep/ 就是把data-v-hash值选择器写到类名的前面 */
//   /deep/ .van-nav-bar__title {
//     color: white;
//   }
// }
</style>
